package ltd.hxya.novel.book.service.impl;



import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.hxya.novel.book.dto.ImgVerifyCodeRespDto;
import ltd.hxya.novel.book.entity.UserInfo;
import ltd.hxya.novel.book.mapper.UserInfoMapper;
import ltd.hxya.novel.book.service.UserInfoService;
import ltd.hxya.novel.book.utils.constant.CacheConsts;
import ltd.hxya.novel.book.utils.resp.ImgVerifyCodeUtils;
import ltd.hxya.novel.book.utils.resp.RestResp;
import ltd.hxya.novel.common.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.Duration;


/**
 * @author ZWW
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;




    /**
     * 获取图片验证码接口
     * 把图片存在了redis中，并且设置了时间
     * @return
     */
    @Override
    public Result<ImgVerifyCodeRespDto> getImgVerifyCode() {
        String uuid = IdWorker.get32UUID();
        return Result.success(ImgVerifyCodeRespDto.builder()
                .sessionId(uuid)
                .img(getImgVerifyCode(uuid))
                .build());
    }


    /**
     * 生成图片，并且存到redis中，redis中的key就是
     * @param sessionId
     * @return
     */
    public String getImgVerifyCode(String sessionId){
        String randomVerifyCode = ImgVerifyCodeUtils.getRandomVerifyCode(4);
        String img = null;
        try {
            img = ImgVerifyCodeUtils.genVerifyCodeImg(randomVerifyCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 存到redis中，然后时间要设置成5min
        stringRedisTemplate.opsForValue().set(CacheConsts.IMG_VERIFY_CODE_CACHE_KEY + sessionId,
                randomVerifyCode, Duration.ofMinutes(5));
        return img;
    }
}
